package com.yc.DAO;

import com.yc.bean.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import javax.swing.plaf.basic.BasicTreeUI;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

/**
 * @ClassName AccountTemplateImpl
 * @since: 2023/8/3 10:50
 * @auth: kirito
 * @description:
 **/
@Repository
public class AccountTemplateImpl implements AccountDao{
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void init(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
    @Override
    public int insert(double money) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(con -> {
            PreparedStatement ps = con.prepareStatement(
                    "insert into bank(balance) values(?)", new String[]{"accountid"});
            ps.setString(1, money+"");
            return ps;
        },keyHolder);
        return keyHolder.getKey().intValue();
    }

    @Override
    public void update(int accountid,double money) {
        jdbcTemplate.update(
                "update bank set banlance = balance+? where account = ?",
                money+"",accountid+"");
    }

    @Override
    public void delete(int accountid) {
        jdbcTemplate.update(
                "delete from bank where accountid = ?",
                Integer.valueOf(accountid)
        );
    }

    @Override
    public int findCount() {
        int rowCount = jdbcTemplate.queryForObject(
                "select count(*) from bank", Integer.class);
        return 0;
    }

    @Override
    public List<Account> findAll() {
        List<Account> list = jdbcTemplate.query(
                "select * from bank",
                (rs, rowNum) -> {
                    Account a = new Account();
                    a.setAccountid(rs.getInt(1));
                    a.setBalance(rs.getDouble(2));
                    return a;
                });
        return list;
    }

    @Override
    public Account findById(int accountid) {
        Account account = jdbcTemplate.queryForObject(
                "select * from bank where accountid = ?",
                (rs, rowNum) -> {
                    Account a = new Account();
                    a.setAccountid(rs.getInt(1));
                    a.setBalance(rs.getDouble(2));
                    return a;
                },accountid);
        return null;
    }
}
